﻿using System.Web.Mvc;
using System.Linq;
using CMSMVC4.Filters;
using CMSMVC4.Areas.Admin.Models;

namespace CMSMVC4.Areas.Admin.Controllers
{
    [Authorize(Roles = "Admin,Background")]
    public class BackgroundController : Controller
    {
        readonly CMSMVC4Entities _db = new CMSMVC4Entities();
        //
        // GET: /Admin/Background
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/Background").Rows[0]["Parrent"];

            var data = new CommandSql().GetAllBackground();

            return View(data);
        }

        //
        //GET: /Admin/Background/Add
        [HttpGet]
        public ActionResult Add()
        {
            ViewBag.M = new CommandSql().GetParrentByMenu("/Admin/Background/Add").Rows[0]["Parrent"];
            
            return View();
        }

        [HttpPost]
        public ActionResult Add(BackgroundModels models)
        {
            if (ModelState.IsValid)
            {
                var baner = new Baner {Type = BanerStatus.Background, Name = models.Name, Url = models.Url,Status = CategoriStatus.Nhap};
                _db.Baners.AddObject(baner);
                _db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        //
        //GET: /Admin/Background/Active
        [HttpGet]
        public ActionResult Active(int id)
        {
            var data1 = _db.Baners.Where(x => x.Type == BanerStatus.Background && x.Status == CategoriStatus.Thuong).ToList();
            foreach (var baner in data1)
            {
                baner.Status = CategoriStatus.Nhap;
            }
            var data = _db.Baners.FirstOrDefault(x => x.Id == id && x.Type == BanerStatus.Background);
            if (data != null) data.Status = CategoriStatus.Thuong;
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        //
        //GET: /Admin/Background/Delete
        [HttpGet]
        public ActionResult Delete(int id)
        {
            return PartialView();
        }

        [HttpPost]
        public ActionResult Delete(string[] id)
        {
            if (id != null)
            {
                foreach (var i in id)
                {
                    int idcomment;
                    int.TryParse(i, out idcomment);
                    var row = _db.Baners.FirstOrDefault(x => x.Id == idcomment);
                    _db.Baners.DeleteObject(row);
                    _db.SaveChanges();
                }
            }
            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
    }
}
